﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Entity.Validation;
using HYI.SDBSERVER;
using eHCBaseClass;
using Sunny.UI;

namespace SHRSYSTEM
{
    public partial class FMI_TS_SCENE_HEAD : SDBSERVER.FMSINGLE
    {
        //入口函数
        public static Int32 StartMe(string sMainPara, string sPara, string sUser, DBSERVER sDB)
        {
            StaticClass.Selectm_MainPara = sMainPara;
            StaticClass.SelectItemValue = sPara;
            StaticClass.SelectUser = sUser;
            StaticClass.myDB = sDB;
            return 0;
        }

        //DBSERVER myADO = new DBSERVER();
        DBCache myCache = new DBCache();
        private int iGridView = 0;
        private int iGridView2 = 0;
        private int detailindex = -1;
        private string sSite_No;
        private string sType = "V";
        DataTable myDetail;

        public FMI_TS_SCENE_HEAD()
        {
            InitializeComponent();
        }

        //查询代码
        protected override void OnSys04()
        {
            string SQL = " select b.fdictname,a.*"
              + " from i_ts_scene_head a,s_ts_dict b"
              + " where b.fdicttype = 3001 and b.fdictno = a.fstorageflag";
            DataRowView drv = (DataRowView)uiCBfstorageflag.SelectedItem;
            if ((drv != null) && (uiCBfstorageflag.SelectedIndex > 0))
            {
                string sfstorageflag = drv.Row["fDictNo"].ToString();
                SQL = SQL + " and b.fdictno='" + sfstorageflag + "'";
            }
            if (qifscenename.Text != "")
            {
                SQL = SQL + " and ((a.fsceneno like '%" + qifscenename.Text + "%') or (a.fscenename like '%" + qifscenename.Text + "%'))";
            }
            SQL = SQL + "  order by b.fdictname";
            Qrytable = StaticClass.myDB.query(SQL);

            base.OnSys04();
            
            rowindex = -1;
        }

        private void FMI_TS_SCENE_HEAD_Load(object sender, EventArgs e)
        {
            sUser = StaticClass.SelectUser;
            string[] strArray = StaticClass.Selectm_MainPara.Split(new char[] { ';' });
            sMenu = strArray[1];
            sSite_No = strArray[0];

            //按钮控制
            sys05.Visible = false; sys05.Tag = "1";
            sys06.Visible = false; sys06.Tag = "1";
            sys07.Visible = false; sys07.Tag = "1";
            sys08.Visible = false; sys08.Tag = "1";
            sys09.Visible = false; sys09.Tag = "1";
            sys11.Visible = false; sys11.Tag = "1";

            //下拉框
            DataTable myTs_Dict = myCache.doGetDict("S_TS_DICT", "fDictType=3001");
            uifstorageflag.DataSource = myTs_Dict;
            uifstorageflag.DisplayMember = "fDictName";
            uifstorageflag.ValueMember = "fDictNo";

            DataRow dr1 = myTs_Dict.NewRow();
            dr1["fDictName"] = "请选择";
            dr1["fDictNo"] = "0";
            myTs_Dict.Rows.InsertAt(dr1, 0);
            uiCBfstorageflag.DataSource = myTs_Dict;
            uiCBfstorageflag.DisplayMember = "fDictName";
            uiCBfstorageflag.ValueMember = "fDictNo";
            uiCBfstorageflag.SelectedIndex = 0;

            //执行查询代码
            OnSys04();

            //表格列显示统一控制
            if (iGridView == 0)
            {
                myCache.doSetGridVIew(sMenu, sUser, uiDGView);
                iGridView = iGridView + 1;
            }
        }

        //新增代码
        protected override void OnSys01()
        {
            uifscenename.Text = "";
            uifstorageflag.SelectedIndex = 0;

            DataTable myNo = StaticClass.myDB.query("exec fun_billnumber 2000");
            if ((myNo != null) && (myNo.Rows.Count > 0))
            {
                uifsceneno.Text = int.Parse(myNo.Rows[0][0].ToString()).ToString();
            }
            sType = "A";
            doLoadData();
            uifsceneno.ReadOnly = false;

            base.OnSys01();
        }

        //编辑+浏览载入数据
        private void doLoadData()
        {
            //控制界面输入
            Boolean input = false;
            if ((sType.Equals("A")) || (sType.Equals("B")))
            {
                input = false;
            }
            else
            {
                input = true;
            }
            foreach (Control ctrl in uiPanel1.Controls)
            {
                if (ctrl is UITextBox)
                {
                    UITextBox m = (UITextBox)ctrl;
                    m.ReadOnly = input;
                }

                if (ctrl is UIComboBox)
                {
                    UIComboBox m = (UIComboBox)ctrl;
                    m.ReadOnly = input;
                }
            }

            if (!sType.Equals("A"))
            {
                uifsceneno.Text = uiDGView["fsceneno", rowindex].Value.ToString();
                uifscenename.Text = uiDGView["fscenename", rowindex].Value.ToString();

                int i = 0;
                string sfstorageflag = uiDGView["fstorageflag", rowindex].Value.ToString();
                foreach (System.Data.DataRowView dr in uifstorageflag.Items)
                {
                    string id = dr["fdictno"].ToString();
                    if (id.Equals(sfstorageflag))
                    {
                        uifstorageflag.SelectedIndex = i;
                        break;
                    }
                    i = i + 1;
                }
                
            }

            //载入明细
            string sql = "select a.fno,b.fairname,a.fwhere,a.fvalue,a.fwhere2,a.fvalue2,a.fairitem"
                + " from i_ts_scene_item a,s_ts_airitem b"
                + " where a.fairitem = b.fairitem"
                + " and a.fsceneno=" + uifsceneno.Text
                + " order by fno";
            myDetail = StaticClass.myDB.query(sql);
            uiDetail.DataSource = myDetail;

            //表格列显示统一控制
            if (iGridView2 == 0)
            {
                myCache.doSetGridVIew(sMenu + "1", sUser, uiDetail);
                iGridView2 = iGridView2 + 1;
            }

            uibtn1.Visible = true;
            uibtn2.Visible = true;
            uiPanel1.Height = 115;

            if (sType.Equals("V"))
            {
                uibtn1.Visible = false;
                uibtn2.Visible = false;
                uiPanel1.Height = 65;
            }

        }

        //编辑代码
        protected override void OnSys02()
        {
            Console.WriteLine("行:" + rowindex.ToString());
            if (rowindex == -1)
            {
                return;
            }
            sType = "B";

            doLoadData();

            uifsceneno.ReadOnly = true;

            base.OnSys02();
        }

        //删除代码
        protected override void OnSys03()
        {
            Console.WriteLine("行:" + rowindex.ToString());
            if (rowindex == -1)
            {
                return;
            }

            if (this.ShowAskDialog("确定删除(" + uiDGView["fscenename", rowindex].Value.ToString() + ")?"))
            {
                string sBillNo = uiDGView["fsceneno", rowindex].Value.ToString();
                string SQL = "exec proc_biz_dodelete 'i_ts_scene_head','','" + sBillNo + "',2,'" + sUser + "'";
                DataTable myTable = StaticClass.myDB.query(SQL);

                string sMsg = myTable.Rows[0][0].ToString();
                if (sMsg.Equals("OK"))
                {
                    this.ShowInfoDialog("删除完毕");
                    myCache.doCache();
                    OnSys04();
                }
                else
                {
                    this.ShowInfoDialog(sMsg);
                }
            }
        }

        //浏览代码
        protected override void OnSys10()
        {
            Console.WriteLine("行:" + rowindex.ToString());
            if (rowindex == -1)
            {
                return;
            }
            sType = "V";

            doLoadData();

            base.OnSys10();

        }

        //数据为空检查
        private bool CheckData()
        {
            return CheckEmpty(uifstorageflag, "请选择存储分类")
                   && CheckEmpty(uifscenename, "请输入场景内容");
        }

        //保存代码
        protected override void OnSys08()
        {
            if (!CheckData())
            {
                return;
            }
            DataRowView drv1 = (DataRowView)uifstorageflag.SelectedItem;
            string sfstorageflag = drv1.Row["fDictNo"].ToString();

            if (sType == "A")
            {
                try
                {
                    using (XTBasEntities context = new XTBasEntities())
                    {
                        i_ts_scene_head myData = context.i_ts_scene_head.Find(int.Parse(uifsceneno.Text));
                        if (myData is null)
                        {
                            i_ts_scene_head myData2 = new i_ts_scene_head();
                            myData2.fsceneno = int.Parse(uifsceneno.Text);
                            myData2.fscenename = uifscenename.Text;
                            myData2.foperator = sUser;
                            myData2.fupddate = DateTime.Now;
                            myData2.fsite_no = sSite_No;
                            myData2.fscenetype = 1;
                            myData2.fstorageflag = sfstorageflag;
                            context.i_ts_scene_head.Add(myData2);
                            context.SaveChanges();

                            doSetDetail();
                            UIMessageTip.ShowOk("添加成功");

                        }
                        else
                        {
                            //Console.WriteLine("添加成功");
                            UIMessageTip.ShowOk("编号已存在");
                            //Console.WriteLine("已存在");
                            return;
                        }

                    }
                }
                catch (DbEntityValidationException dbEx)
                {
                    Console.WriteLine("错误" + dbEx.Message);
                }
            }

            else if (sType == "B")
            {
                using (XTBasEntities context = new XTBasEntities())
                {
                    //查询
                    i_ts_scene_head myscene_head = context.i_ts_scene_head.Find(int.Parse(uifsceneno.Text));

                    myscene_head.fscenename = uifscenename.Text;
                    myscene_head.foperator = sUser;
                    myscene_head.fupddate = DateTime.Now;
                    myscene_head.fstorageflag = sfstorageflag;
                    int result = context.SaveChanges();
                    doSetDetail();
                    UIMessageTip.ShowOk("修改成功");
                }
            }

            //刷新cache
            sType = "V";
            base.OnSys08();

            OnSys04();
        }

        //保存明细
        private Boolean doSetDetail()
        {
            bool IsOk = false;
            StaticClass.myDB.SQLList.Clear();
            string sql = "delete from i_ts_scene_item where fsceneno=" + uifsceneno.Text;
            StaticClass.myDB.SQLList.Add(sql);

            for (int i = 0; i < myDetail.Rows.Count; i++)
            {
                sql = "insert into i_ts_scene_item(fsceneno,fno,fairitem,fwhere,fvalue,fwhere2,fvalue2)"
                    + " values('" + uifsceneno.Text + "'"
                    + "," + myDetail.Rows[i]["fno"].ToString()
                    + ",'" + myDetail.Rows[i]["fairitem"].ToString() + "'"
                    + ",'" + myDetail.Rows[i]["fwhere"].ToString() + "'"
                    + "," + myDetail.Rows[i]["fvalue"].ToString()
                    + ",'" + myDetail.Rows[i]["fwhere2"].ToString() + "'"
                    + "," + myDetail.Rows[i]["fvalue2"].ToString()
                    + ")";
                StaticClass.myDB.SQLList.Add(sql);
            }

            sql = "delete from i_tc_scene_view where fsceneno=" + uifsceneno.Text;
            StaticClass.myDB.SQLList.Add(sql);

            sql = "insert into i_tc_scene_view(fsceneno,fsite_no,fstorageflag,fairitem,fwhere,fvalue,fwhere2,fvalue2)"
             + " select a.fsceneno,fsite_no,fstorageflag,fairitem,fwhere,fvalue,fwhere2,fvalue2"
             + " from i_ts_scene_item a, i_ts_scene_head b"
             + " where  b.fsceneno=" + uifsceneno.Text
             + " and a.fsceneno = b.fsceneno";
            StaticClass.myDB.SQLList.Add(sql);

            string sError = string.Empty;
            StaticClass.myDB.doSave(out IsOk, out sError);
            return IsOk;
        }

        private void uiDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            detailindex = e.RowIndex;
        }

        private void uiDetail_DoubleClick(object sender, EventArgs e)
        {
            string iMenu = sMenu + "1";
            OnGridDbClick(iMenu, uiDetail);
        }

        private void uibtn1_Click(object sender, EventArgs e)
        {
            //添加明细 a.fseq,a.fequipmentbarcode,b.fmacno,b.fequipmenttag fcatname
            int i = 1;
            if (myDetail.Rows.Count > 0)
            {
                i = int.Parse(myDetail.Rows[myDetail.Rows.Count - 1]["fno"].ToString()) + 1;
            }

            //弹窗选择
            string sql = "select fairitem, fairname from s_ts_airitem where 1=1";

            string DATA = doPOPWINDOS("存储分类查询"
                , "fairitem,项目编号,121;fairname,项目名称,161"
                , sql
                , " order by fairitem"
                , 1);
            Console.WriteLine("当前返回:" + DATA);

            if ((DATA is null) || (DATA.Length == 0))
            {
                return;
            }
            string[] strList = DATA.Split(';');

            for (int j = 0; j < strList.Length; j++)
            {
                string[] strArray = strList[j].Split(',');

                if (strArray.Length > 1)
                {
                    //存在不保存
                    DataRow[] foundRow = myDetail.Select("fairitem = '" + strArray[0] + "'");
                    if (foundRow.Length == 0)
                    {
                        DataRow dr = myDetail.NewRow();
                        dr["fno"] = i.ToString(); ;
                        dr["fairitem"] = strArray[0];
                        dr["fairname"] = strArray[1];
                        dr["fwhere"] = ">";
                        dr["fvalue"] = "0";
                        dr["fwhere2"] = "<=";
                        dr["fvalue2"] = "1";
                        myDetail.Rows.InsertAt(dr, myDetail.Rows.Count);

                        i = i + 1;
                    }
                }
            }
        }

        private void uibtn2_Click(object sender, EventArgs e)
        {
            //删除明细
            Console.WriteLine("行:" + detailindex.ToString());
            if (detailindex == -1)
            {
                UIMessageTip.ShowOk("请先选择要删除的记录");
                return;
            }
            if (this.ShowAskDialog("确定删除吗?"))
            {
                string iseq = myDetail.Rows[detailindex]["fno"].ToString();
                DataRow[] foundRow = myDetail.Select("fno = " + iseq, "");
                foreach (DataRow row in foundRow)
                {
                    myDetail.Rows.Remove(row);
                }
            }
        }

        private void uiCBfstorageflag_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (iGridView > 0)
            {
                OnSys04();
            }
        }
    }
}
